<?php

namespace App\Http\Controllers\Api;

use App\Model\Carousel;
use App\Model\Goods;
use App\Model\Cart;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class IndexController extends Controller
{
    const pageNum = 8;
    /**
     * 首页接口
     */
    public function index(){
        $carousel = new Carousel();
        $goods = new Goods();
        $data = array();
        //轮播图
        $data['carouselInfo'] = $carousel->select('id','imgurl')->orderBy('created_at','desc')->get();
        $data['goodsInfo'] = $goods->where('status','=','1')->orderBy('num','desc')->skip(0)->take(self::pageNum)->get();
        if(count($data)>0){
            $this->success($data);
        }else{
            $this->error('网络异常'.__CLASS__.__LINE__);
        }
    }

    //加在更多商品
    public function moreGoods(Request $request){
        $goods = new Goods();
        $page = $request->input("page");
        $num = $page * self::pageNum;
        $goodsInfo = $goods->where('status','=','1')->orderBy('num','desc')->skip($num)->take(self::pageNum)->get();
        if(count($goodsInfo) > 0){
            $this->success($goodsInfo);
        }else{
            $this->error('没有更多数据了！');
        }
    }

    /**
     * @param Request $request
     * 添加到购物车
     */
    public function addCart(Request $request){
        $goods = new Goods();
        $cart = new Cart();
        $uid = $request->input("user_id");
        $gid = $request->input("goods_id");
        $goodsInfo = $goods->where('status','1')->find($gid);
        if(empty($uid) || empty($gid)){
            $this->error('参数错误');
        }

        $cartInfo = $cart->where('user_id',$uid)->where('goods_id',$gid)->first();
        if(count($cartInfo)>0){
            if($goodsInfo['num'] < ($cartInfo['num']+1)){
                $this->error('库存不足');
            }else{
                $countNum = $cartInfo['num']+1;
                $res = $cart->where('id',$cartInfo['id'])->update(array('num'=>$countNum));
            }
        }else{
            $cart = new Cart();
            $cart->user_id = $uid;
            $cart->goods_id = $gid;
            $cart->num = 1;
            $cart->price = $goodsInfo['price'];
            $res = $cart->save();
        }
        if($res){
            $this->success('添加购物车成功！');
        }else{
            $this->error('添加失败'.__LINE__);
        }
    }
}
